package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
	"strconv"
	"time"
)

type loginResp struct {
	Status   string `json:"status"`
	Message  string `json:"message"`
	Formhash string `json:"formhash"`
}

type signResp struct {
	Status  string `json:"status"`
	Message string `json:"message"`
}

func login(username, password, questionAnswer string, questionNum int, msg *[]string) (formhash string, cookie []*http.Cookie) {
	url := `https://www.t00ls.cc/login.json`
	header := make(map[string]string)
	header["Content-Type"] = "application/x-www-form-urlencoded"
	header["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36"
	request := myRequest{url: url, method: "POST", data: fmt.Sprintf("action=login&username=%s&password=%s&questionid=%d&answer=%s",
		username, password, questionNum, questionAnswer), header: &header, ssl: true}
	resp, err := request.send()
	if err != nil {
		log.Println(err.Error())
		return
	}
	defer resp.Body.Close()
	//{"status":"success","message":"loginsuccess","formhash":"8bd2bba2"}
	respdata := loginResp{}
	context, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	err = json.Unmarshal(context, &respdata)
	if err != nil {
		log.Println(err.Error())
		return
	}
	if respdata.Status != "success" {
		*msg = append(*msg, fmt.Sprintf("%s login T00ls fail.", username))
		log.Printf("%s login T00ls fail.\n", username)
		return
	}
	log.Println("tools login success!")
	*msg = append(*msg, fmt.Sprintf("%s login T00ls Success.", username))
	cookie = resp.Cookies()
	formhash = respdata.Formhash
	return
}

func sign(formhash string, cookie []*http.Cookie, msg *[]string) (sig bool) {
	sig = false
	url := "https://www.t00ls.cc/ajax-sign.json"
	data := fmt.Sprintf("formhash=%s&signsubmit=true", formhash)
	header := make(map[string]string)
	header["Content-Type"] = "application/x-www-form-urlencoded"
	header["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36"

	request := myRequest{url: url, method: "POST", ssl: true, data: data, header: &header, cookie: cookie}
	resp, err := request.send()
	if err != nil {
		log.Println(err.Error())
		return
	}
	defer resp.Body.Close()
	context, _ := ioutil.ReadAll(resp.Body)
	signresp := signResp{}
	_ = json.Unmarshal(context, &signresp)
	if signresp.Status == "success" {
		*msg = append(*msg, "签到成功，TuBi + 1")
		log.Println("签到成功，TuBi + 1")
		sig = true
	} else {
		if signresp.Message == "alreadysign" {
			*msg = append(*msg, "重复签到，今天已成功签到!")
			log.Println("重复签到，今天已成功签到")
			sig = true
		} else {
			*msg = append(*msg, "签到接口异常")
			log.Println("签到接口异常")
		}
	}
	return
}

func queryDomainRs(formhash string, cookie []*http.Cookie, domains []string, msg *[]string, username string) (sig bool) {
	sig = false
	url := `https://www.t00ls.cc/domain.html`
	header := make(map[string]string)
	header["Content-Type"] = "application/x-www-form-urlencoded"
	header["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36"
	tubiNum := 0
	var err error
	for {
		tubiNum, err = strconv.Atoi(queyTuBi(cookie))
		if err != nil {
			time.Sleep(time.Second * 2)
		}
		break
	}

	for _, domain := range domains {
		data := fmt.Sprintf(`domain=%s&formhash=%s&querydomainsubmit=%%E6%%9F%%A5%%E8%%AF%%A2`, domain, formhash)
		request := myRequest{url: url, method: "POST", header: &header, cookie: cookie, ssl: true, data: data}
		num := 0
		for {
			resp, err := request.send()
			time.Sleep(time.Second * 3)
			if err != nil {
				log.Printf("Domain %s query fail.\n", domain)
				*msg = append(*msg, fmt.Sprintf("Domain %s 签到响应失败.", domain))
				num += 1
				if num <= 3 {
					for i := 0; i < 3; i++ {
						Num, err1 := strconv.Atoi(queyTuBi(cookie))
						if err1 != nil {
							*msg = append(*msg, fmt.Sprintf("Tubi 查询接口调用失败 %d 次", i+1))
						} else {
							if Num > tubiNum {
								*msg = append(*msg, fmt.Sprintf("域名 %s 虽然响应失败但实际查询成功,增加TuBi +1", domain))
								sig = true
								return
							}
							break
						}
						time.Sleep(time.Second * 2)
					}
					continue
				}
			} else {
				resp.Body.Close()
				*msg = append(*msg, fmt.Sprintf("Domain %s 签到响应成功.", domain))
				for i := 0; i < 3; i++ {
					Num, err1 := strconv.Atoi(queyTuBi(cookie))
					if err1 != nil {
						*msg = append(*msg, fmt.Sprintf("Tubi 查询接口调用失败 %d 次", i+1))
					} else {
						if Num > tubiNum {
							*msg = append(*msg, fmt.Sprintf("%s 域名 %s 查询成功,增加TuBi +1", username, domain))
							sig = true
							return
						} else {
							*msg = append(*msg, fmt.Sprintf("域名 %s 查询成功，但TuBi没有增加，可能是重复域名", domain))
						}
						break
					}
					time.Sleep(time.Second * 2)
				}
			}
			break
		}
	}
	return
}

func queyTuBi(cookie []*http.Cookie) (tubi string) {
	url := `https://www.t00ls.cc/members-profile-12513.html`
	resultRequest := myRequest{url: url, method: "GET", cookie: cookie, ssl: true}
	for i := 0; i < 3; i++ {
		resp, err := resultRequest.send()
		if err != nil {
			log.Println(err.Error())
		} else {
			context, _ := ioutil.ReadAll(resp.Body)
			resp.Body.Close()
			reg := regexp.MustCompile(`>TuBi</td>\r\n<td class="data"><p>(\d+)</p></td>`)
			rs := reg.FindStringSubmatch(string(context))
			if len(rs) != 0 {
				tubi = rs[1]
				break
			}
		}
		time.Sleep(time.Second)
	}
	return
}
